const {
    globalData
  } = getApp()
  var network = require("../../utils/network.js")
  Page({
    data: {
      companyName: "",
      contacts: "",
      phone: "",
      auth_code: "",
      legal_person_phone: "",
      legal_person: "",
      description: "",
      region: ['', '', ''],
      hazardousRelated: false,
      cert_number: "",
      countTimer: null, //倒计时计时器
      countNum: 60, //倒计秒
      showCount: false, //是否展示倒计时
      business_license_file: {},
      hazardous_file: {},
      traffic_file: {},
      other_file: {},
      sup_id: "",
    },
    onUnload(){
        clearInterval(this.data.countTimer)
        this.setData({
            countTimer: null,
            showCount: false,
            countNum: 60
        })
    },
    
    changeSelect() {
      this.setData({
        hazardousRelated: !this.data.hazardousRelated
      })
    },
    /**
     * 获取用户已填的认证信息
     */
    getBasicData() { //获取更新前数据
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      let self = this;
      network.GET({
        url: "/new/user/getCert",
        success: function (res) {
          if (res.data.code === 0) {
            let data = res.data.data.supplier_info;
            self.setData({
              sup_id: data.sup_id?data.sup_id:'',
              companyName: data.company_name?data.company_name:'',
              contacts: data.contacts?data.contacts:'',
              phone: data.phone?data.phone:'',
              legal_person_phone: data.legal_person_phone?data.legal_person_phone:'',
              legal_person: data.legal_person?data.legal_person:'',
              description: data.synopsis?data.synopsis:'',
              region: [data.province, data.city, data.district],
              address: data.address?data.address:'',
              short_name: data.short_name?data.short_name:'',
              cert_number: data.cert_number?data.cert_number:'',
              established_time: data.established_time?data.established_time:'',
              hazardousRelated: data.hazardous_related == 1 ? true : data.hazardous_related == 0 ? false : false,
              business_license_file: {
                  src:data.business_license_path?globalData.api_url + data.business_license_path:'',
                  fileName: ""
              },
              hazardous_file: {
                  src: data.hazardous_path?globalData.api_url + data.hazardous_path:'',
                  fileName: ""
              },
              traffic_file: {
                  src: data.traffic_path?globalData.api_url + data.traffic_path:'',
                  fileName:""
              },
              other_file: {
                  src:data.other_path?globalData.api_url + data.other_path:'',
                  fileName:""
              }
            })
          } 
          wx.hideLoading()
        },
        fail: function () {
          //失败后
          wx.hideLoading()
        },
      })
    },
    // 上传相关
    // (1)选择本地、拍照上传图片
    chooseImageTap(e) {
      let _this = this
      wx.showActionSheet({
        itemList: ['本地上传', '拍照上传'],
        itemColor: '#000000',
        success: function (res) {
          if (res.tapIndex === 0) {
            _this.chooseWxImage('album', e.currentTarget.dataset.name)
          } else if (res.tapIndex === 1) {
            _this.chooseWxImage('camera', e.currentTarget.dataset.name)
          }
        },
        fail: function (e) {
          console.error(e)
        }
      })
    },
    // (2)图片选择后的回调方法
    chooseWxImage(type, name) {
      const self = this
      let count = 1
      wx.chooseImage({
        count: count,
        sizeType: ['original', 'compressed'],
        sourceType: [type],
        success: function (res) {
            console.log(res.tempFilePaths[0],'000111')
          wx.showLoading({
            title: '图片上传中...',
            mask: true
          })
          let str = true
          self.upImg(res.tempFilePaths[0], str, name)
        },
        fail: function (e) {
          console.error(e)
        }
      })
    },
    // (3)图片选择后的,上传到服务器
    upImg(path, str, name) {
      let self = this
      const header = {
        'content-type': 'multipart/form-data'
      }
      const loginInfo = (globalData && globalData.loginInfo) || wx.getStorageSync('loginInfo');
      if (loginInfo && loginInfo.cookie) {
        header["Cookie"] = loginInfo.cookie;
      }
      wx.uploadFile({
        url: globalData.api_url + `/new/pub/upload`,
        filePath: path,
        name: 'file',
        header: header,
        formData: {
            'type': 'confirm'
        },
        success: function (res) {
          let data = JSON.parse(res.data)
          if (data.code == 0) {
            self.setData({
              [name]: {
                  src: data.data.src,
                  fileName: data.data.file_name
              }
            })
            if (str) {
              wx.hideLoading()
            }
          } else {
            wx.hideLoading()
          }
        },
        fail: function () {
          console.error('上传图片失败')
          wx.hideLoading()
        }
      })
    },
    /**
     * 发送短信验证码 
     */
    send_code(){
        var  re = /^1\d{10}$/    //正则表达式
        if(this.data.legal_person_phone.trim() === ""){
            wx.showToast({
                title: "请输入法人电话以获取授权码",
                icon: 'none',
                duration: 1000
            })
        }else if(!(re.test(this.data.legal_person_phone))){
            wx.showToast({
                title: "法人电话格式错误",
                icon: 'none',
                duration: 1000
            })
        }else{
            getApp().network.POST({
                url:"/new/send_code",
                params: {
                    phone: this.data.legal_person_phone,
                    type: "certificate"
                },
                success: (res)=>{
                    if(res.data.code == 0){
                        console.log("发送成功")
                        this.dealCodeCount();
                    }else{
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            duration: 1000
                        })
                    }
                },
                fail: (err)=>{
                    console.log(err)
                }
            })
        }
    },
    /**
     * 验证码倒计时 
     */
    dealCodeCount(){
        this.setData({
            showCount: true,
            countTimer: setInterval(()=>{
                if(this.data.countNum >0){
                    this.setData({
                        countNum: this.data.countNum - 1
                    })
                }else{
                    clearInterval(this.data.countTimer)
                    this.setData({
                        countTimer: null,
                        showCount: false,
                        countNum: 60
                    })
                }
            },1000)
        })
    },
    /**
     * 删除图片
     */
    deleteImg(e) {
      this.setData({
        [e.currentTarget.dataset.name]: {
            src:"",
            fileName:""
        }
      })
    },
    /**
     * 相关字段输入框值变化
     */
    changeValue(e) {
      const valueName = e.currentTarget.dataset.name;
      this.setData({
        [valueName]: e.detail.value
      })
    },
    bindRegionChange(e) {
      this.setData({
        region: e.detail.value
      })
    },
    /**
     * 提交认证信息
     */
    submit() {
      const self = this;
      let tip = "";
      var  re = /^1\d{10}$/    //正则表达式
      if (!this.data.companyName.trim()) {
        tip = "请输入企业名称"
      } else if (!this.data.contacts.trim()) {
        tip = "请输入业务联系人姓名"
      } else if (!this.data.phone.trim()) {
        tip = "请输入联系人电话"
      }else if(!this.data.legal_person.trim()){
        tip = "请输入法人姓名"
      }else if(!this.data.legal_person_phone.trim()){
        tip = "请输入法人电话"
      }else if(!(re.test(this.data.legal_person_phone))){
        tip = "法人电话格式错误"
      } else if(!this.data.auth_code.trim()){
        tip = "请输入法人授权码"
      } else if (!this.data.region[0]) {
        tip = "请选择公司地址"
      } else if (!this.data.address) {
        tip = "请输入详细地址"
      }else if (!this.data.description.trim()) {
        tip = "请输入注册目的"
      } else if (!this.data.business_license_file.src) {
        tip = "请上传营业执照"
      } else if (this.data.hazardousRelated && !this.data.hazardous_file.src) {
        tip = "请上传危险化学品经营许可证"
      }
      if (tip) {
        wx.showToast({
          title: tip,
          icon: 'none',
          duration: 2000
        })
        return;
      }
      let params = {
        company_name: this.data.companyName,
        contacts: this.data.contacts,
        phone: this.data.phone,
        auth_code: this.data.auth_code,
        legal_person_phone: this.data.legal_person_phone,
        legal_person: this.data.legal_person,
        synopsis: this.data.description,
        hazardous_related: this.data.hazardousRelated ? 1 : 0,
        business_license_file: (this.data.business_license_file && this.data.business_license_file.fileName) ? this.data.business_license_file.fileName : "",
        hazardous_file: (this.data.hazardous_file && this.data.hazardous_file.fileName) ? this.data.hazardous_file.fileName : "",
        traffic_file: (this.data.traffic_file && this.data.traffic_file.fileName) ? this.data.traffic_file.fileName : "",
        other_file: (this.data.other_file && this.data.other_file.fileName) ? this.data.other_file.fileName : "",
        province: this.data.region[0],
        city: this.data.region[1],
        district: this.data.region[2],
        address: this.data.address,
        short_name: this.data.short_name,
        cert_number: this.data.cert_number,
        established_time: this.data.established_time,
      }
      if(this.data.sup_id){
          params.sup_id = this.data.sup_id
      }
      network.POST({
        url: "/new/user/cert",
        params: params,
        success: function (res) {
          if (res.data.code === 0) {
            wx.disableAlertBeforeUnload();
            wx.showModal({
                title: '认证成功',
                content: '即将返回我的页面',
                showCancel: false,
                success (res) {
                    if (res.confirm) {
                        wx.redirectTo({
                            url: "/pages/my/my"
                        })
                    }
                }
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'error',
              duration: 2000
            })
          }
        },
        fail: function () {
          //失败后
  
        },
      })
    },
    onLoad() {
      this.getBasicData();
      wx.enableAlertBeforeUnload({
        message: "请检查你是否有未提交的内容，如果没有，可点击“确认”按钮返回上一页!"
      });
    },
  
  
  })